
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
 */
package meeple;

//~--- JDK imports ------------------------------------------------------------

import java.util.ArrayList;

/**
 *
 * @author Rogier
 */
public class FieldCollection {
    ArrayList fields = new ArrayList();
    Integer   max    = 0;

    public int getNewFieldId() {
        int result = max;

        fields.add(max);
        max = fields.size();    // should be equal to  max++

        return result;
    }

    public int joinFieldIds(int[] ids) {
        for (int i : ids) {
            if (!isValidId(i)) {
                return -1;
            }
        }

        int newId = getNewFieldId();

        for (int i : ids) {
            fields.set(i, newId);
        }

        return newId;
    }

    public int getParentField(int id) {
        int old = id;
        int now = (Integer) fields.get(id);

        while (old != now) {
            old = now;
            now = (Integer) fields.get(old);
        }

        return now;
    }

    public boolean isInSameField(int[] ids) {
        if (ids.length >= 2) {    // at east two elements are needed to compare
            int now;
            int old = getParentField(ids[0]);

            for (int i = 1; i < ids.length; i++) {
                now = getParentField(ids[i]);

                if (old != now) {
                    return false;
                }

                old = now;
            }

            return true;
        }

        return true;    // one element is allways in it own field, maybe this should be an exception  call
    }

    boolean isValidId(Integer id) {
        return (id >= 0) && (id < max);
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
